package org.goldfish.message_board01.filters;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.goldfish.message_board01.dao.SensitiveWordDAO;

import java.io.IOException;
import java.util.Map;

public class ContentFilter extends HttpFilter {
    SensitiveWordDAO sensitiveWordDAO;

    public void init() throws ServletException {
        sensitiveWordDAO = new SensitiveWordDAO();
    }

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        if(req.getParameter("content") == null){
            chain.doFilter(req, res);
            return;
        }
        String content = req.getParameter("content");
        if (content == null) {
            chain.doFilter(req, res);
            return;
        }
        Map<String, String> sensitiveWords = sensitiveWordDAO.getSensitiveWords();
        System.out.println(getClass()+"filtering content: " + content);
        System.out.println(sensitiveWords);
        for (Map.Entry<String, String> entry : sensitiveWords.entrySet()) {
            content = content.replaceAll(entry.getKey(), entry.getValue());
        }
        System.out.println("filtered content: " + content);
        req.setAttribute("content", content);
        chain.doFilter(req, res);
    }
}
